package main_panel

import (
	"file_explorer/common/consts"
	"file_explorer/common/log"
	"file_explorer/model"
	"file_explorer/service/eventbus"
	"file_explorer/view/components/main_panel/fe_tab"
	"file_explorer/view/components/main_panel/file_create_tab"
	"file_explorer/view/components/main_panel/file_tab"
	"file_explorer/view/components/main_panel/metadata_tab"
	"file_explorer/view/components/main_panel/rename_tab"
	"file_explorer/view/components/main_panel/search_res_tab"
	"file_explorer/view/components/main_panel/setting_tab"
	"file_explorer/view/components/main_panel/task_list_tab"
	"file_explorer/view/store"

	"fyne.io/fyne/v2/container"
)

type MainPanel struct {
	*container.DocTabs

	gCtx *store.GlobalContext
}

// 新增tab上下文，创建TabItem
func (panel *MainPanel) newTabItem(tabCtx store.TabContext) *container.TabItem {
	var tab fe_tab.FeTab
	tabItem := container.NewTabItemWithIcon(tabCtx.GetTabLabel(), tabCtx.GetTabIcon(), nil)
	tabCtx.SetTabItem(tabItem)

	switch tabCtx.GetTabType() {
	case consts.TabTypeFile:
		tab, _ = file_tab.NewFileTab(tabCtx, panel.DocTabs.Refresh)
	case consts.TabTypeMetadata:
		tab = metadata_tab.NewEditMetadataTab(tabCtx)
	case consts.TabTypeFileCreate:
		tab = file_create_tab.NewFileCreateTab(tabCtx)
	case consts.TabTypeSetting:
		tab = setting_tab.NewSettingTab(tabCtx)
	case consts.TabTypeTaskList:
		tab = task_list_tab.NewTaskListTab(tabCtx)
	case consts.TabTypeRename:
		tab = rename_tab.NewRenameTab(tabCtx)
	case consts.TabTypeSearchRes:
		tab = search_res_tab.NewSearchResTab(tabCtx)
	}

	tabItem.Content = tab.GetContainer()

	tab.GetContainer().Refresh()

	return tabItem
}

func NewMainPanel(gCtx *store.GlobalContext) *MainPanel {
	mainPanel := &MainPanel{
		DocTabs: container.NewDocTabs(),
		gCtx:    gCtx,
	}

	// 新增tabContext时同步新增tabItem
	mainPanel.gCtx.RegisterConsumer(eventbus.EventKeyAddTab, func(event *model.Event) {
		tabCtx := eventbus.GetEventMsg[store.TabContext](event, "tab_ctx")
		tabItem := mainPanel.newTabItem(tabCtx)
		mainPanel.Append(tabItem)
		mainPanel.Select(tabItem)
		log.Info("创建新标签页，标题：%s", tabItem.Text)
	})

	// tabContext删除时关闭tab
	mainPanel.gCtx.RegisterConsumer(eventbus.EventKeyRemoveTab, func(event *model.Event) {
		tabItem := eventbus.GetEventMsg[*container.TabItem](event, "tab_item")
		mainPanel.Remove(tabItem)
		log.Info("移除标签页，标题：%s", tabItem.Text)
	})

	// 初始化时新增file tab
	homeFileTabContext := store.NewFileTabContext(gCtx, "/")
	mainPanel.gCtx.AddTab(homeFileTabContext)

	mainPanel.SetTabLocation(container.TabLocationTop)
	// 手动关闭标签页时删除对应context
	mainPanel.OnClosed = func(tabItem *container.TabItem) {
		gCtx.RemoveTab(tabItem)
		log.Info("关闭标签页，标题：%s", tabItem.Text)

	}
	return mainPanel
}
